<script type="text/javascript">
    var layerIdx;
    var page = 1;

    var jifen = 0;//加减 成功后清0
    var xitongxiaoxi = '';//系统消息


    //layer.msg("页面加载完成，获取数据中。。。。", {time: 1000,});
    $(document).ready(function (e) {
        // 展示表格
        @if (!empty($tr))
            let trJson = {!! json_encode($tr) !!};
            let trHtml = ''
            for (var i = 0; i < trJson.length; i++) {
                trHtml += trJson[i];
            }
            $(".table tbody").html(trHtml);
        @endif

        // 展示分页
        @if (!empty($total))
        showCount();
        @endif
    });

    // 筛选最大时间与最小时间
    /*var datemin = {
        elem: '#datemin',
        format: 'YYYY-MM-DD',
        max: laydate.now(), //最大日期
        istoday: true,
        choose: function(datas){
            datemax.min = datas; //开始日选好后，重置结束日的最小日期
            datemax.start = datas //将结束日的初始值设定为开始日
        }
    };
    var datemax = {
        elem: '#datemax',
        format: 'YYYY-MM-DD',
        max: laydate.now(),
        istoday: true,
        choose: function(datas){
            datemin.max = datas; //结束日选好后，重置开始日的最大日期
        }
    };
    laydate.skin('molv');
    laydate(datemin);
    laydate(datemax);*/

    // 搜索数据
    function getSearch() {
        let searchs = {};
        searchs['r'] = Math.random()

        @if (!empty($search))
        @foreach($search as $_field => $_title)
        //console.log($("#{{$_field}}").val())
        searchs['{{$_field}}'] = $("#search_{{$_field}}").val();
        @endforeach
        @endif

        @if (!empty($searchHide))
        @foreach($searchHide   as  $_field )
        //console.log($("#{$_field}").val())
        searchs['{{$_field}}'] = $("#{{$_field}}").val();
        @endforeach
        @endif

            return searchs
    }

    // 改变：排序
    function changeSort(e, field) {
        let url = $(e).data('url');
        let sort = $(e).val();

        changeItemValue(url, {[field]: sort});
    }

    // 改变：排序
    function changeInput(e, field) {
        let url = $(e).data('url');
        let sort = $(e).val();

        changeItemValue(url, {[field]: sort});
    }


    // 改变：排序
    function changeSelect(e, field) {
        let url = $(e).data('url');
        let sort = $(e).val();

        changeItemValue(url, {[field]: sort});
    }

    // 改变数据值
    function changeItemValue(url, data) {
        $.ajax({
            type: "POST",
            async: false,
            dataType: "json",
            url: url,
            data: data,
            error: function (XmlHttpRequest, textStatus, errorThrown) {
            },
            success: function (ret) {
                layer.msg(ret.msg, {time: 2000,});
                setTimeout(function () {
                    //window.location.href = '{{$init_url}}';
                    getPageList();
                }, 2000);
            },
            complete: function () {
                layer.close(layerIdx);
            }
        });
    }

    // 展示页面
    function showCount() {
        let _total = "{{$total}}";
        let _pages = "{{$pages}}";

        //$("#totalNums").text(_total);
        if (_pages > 0) {
            laypage({
                cont: $('.page'), //容器。值支持id名、原生dom对象，jquery对象,
                count: _total, //总页数
                pages: _pages, //总页数
                skip: _pages > 10 ? true : false, //是否开启跳页
                skin: '#AF0000',
                groups: 6, //连续显示分页数
                curr: 1,
                jump: function (obj, first) { //触发分页后的回调
                    page = obj.curr;

                    // 展示页面
                    //  第一次展示 且 已经有了列表 则不在暂时
                    if(first){
                        @if (empty($tr))
                        getPageList();
                        @endif
                    }else{
                        getPageList();
                    }
                }
            });
        } else {
            layer.msg("暂无记录");
            $(".table tbody,.page").html("");
        }
    }

    // 获取页数：搜索的时候使用
    function getPageCount() {
        let searchs = getSearch();

        $.ajax({
            beforeSend: function () {
                layerIdx = layer.load();
            },
            type: "POST",
            async: false,
            dataType: "json",
            url: "{{url('/innerend/'.$controller.'/on-count')}}",
            data: searchs,
            error: function (XmlHttpRequest, textStatus, errorThrown) {

            },
            success: function (ret) {
                if (ret.code==200) {
                    $("#totalNums").text(ret.data.total);
                    if (ret.data.pages > 0) {
                        laypage({
                            cont: $('.page'), //容器。值支持id名、原生dom对象，jquery对象,
                            pages: ret.pages, //总页数
                            skip: ret.pages > 10 ? true : false, //是否开启跳页
                            skin: '#AF0000',
                            groups: 6, //连续显示分页数
                            curr: 1,
                            jump: function (obj, first) { //触发分页后的回调
                                page = obj.curr;
                                getPageList();
                            }
                        });
                    } else {
                        layer.msg("暂无记录");
                        $(".table tbody,.page").html("");
                    }
                }
            },
            complete: function () {
                layer.close(layerIdx);
            }
        });
    }

    // 获取带翻页的列表
    function getPageList() {
        //var keyword = $("#keyword").val();
        // 搜索的条件
        let searchs = getSearch();
        searchs['page'] = page

        $.ajax({
            beforeSend: function () {
                layerIdx = layer.load();
            },
            type: "POST",
            async: false,
            dataType: "json",
            url: "{{url('/innerend/'.$controller.'/on-lists')}}",
            data: searchs,
            error: function (XmlHttpRequest, textStatus, errorThrown) {

            },
            success: function (ret) {
                if (ret.code == 200) {
                    let trHtml = ''
                    for (var i = 0; i < ret.data.tr.length; i++) {
                        trHtml += ret.data.tr[i];
                    }
                    $(".table tbody").html(trHtml);
                }
            },
            complete: function () {
                layer.close(layerIdx);
            }
        });
    }

    // 修改页面
    function onEdit(url, title) {
        var index = layer.open({
            type: 2,
            title: title,
            content: url
        });
        layer.full(index);
    }

    // 状态
    // <input class="btn disabled radius" type="button" value="禁用">
    function changeStatus(url) {
        layer.confirm('您确定要操作该记录？', {
            btn: ['是', '否'] //按钮
        }, function () {
            // 执行 ajax
            $.ajax({
                type: "POST",
                async: false,
                dataType: "json",
                url: url,
                data: {},
                error: function (XmlHttpRequest, textStatus, errorThrown) {
                },
                success: function (ret) {
                    layer.msg(ret.msg, {time: 2000,});
                    setTimeout(function () {
                        //window.location.href = '{{$init_url}}';
                        getPageList();
                    }, 2000);
                },
                complete: function () {
                    layer.close(layerIdx);
                }
            });
        }, function () {
            layer.msg('您已经取消操作！', {
                time: 2000, //20s后自动关闭
                //btn: ['明白了', '知道了']
            });
        });
    }

    // 删除
    function onDelete(url, msg) {
        layer.confirm(msg ? msg : '您确定要删除该记录？', {
            btn: ['是', '否'] //按钮
        }, function () {
            // 执行 ajax
            layer.msg('的确很重要', {icon: 1});
            $.ajax({
                type: "POST",
                async: false,
                dataType: "json",
                url: url,
                data: {},
                error: function (XmlHttpRequest, textStatus, errorThrown) {
                },
                success: function (ret) {
                    layer.msg(ret.msg, {time: 2000,});
                    setTimeout(function () {
                        window.location.href = '{{$init_url}}';
                        //getPageList();
                    }, 2000);
                },
                complete: function () {
                    layer.close(layerIdx);
                }
            });
        }, function () {
            layer.msg('您已经取消操作！', {
                time: 2000, //20s后自动关闭
                //btn: ['明白了', '知道了']
            });
        });
    }

    // 审核操作
    function onVerify() {
        layer.open({
            type: 1,
            skin: 'layui-layer-rim', //加上边框
            area: ['420px', '240px'], //宽高
            content: '<div id="chooseClass">'
                + '<input type="text" value="" id="re_xitongxiaoxi" class="input"/>'
                + '<a href="javascript:;" onclick="doXiaoxiClick();" class="btn btn-success radius">确认</a>'
                + '</div>'
        });
    }


    // 搜索：所有的搜索都可以调用的
    function ajaxSearch(url, obj, field = 'uid', id = 'id', show = 'uid') {
        var keyword = $(obj).val();
        if (keyword == "") return;
        $.ajax({
            beforeSend: function () {
                //layerIdx=layer.load();
            },
            type: "POST",
            async: false,
            dataType: "json",
            url: url,
            data: {
                keyword: keyword,
                r: Math.random()
            },
            error: function (XmlHttpRequest, textStatus, errorThrown) {

            },
            success: function (ret) {
                if (ret.code == 200) {
                    var html = '';
                    for (var i = 0; i < ret.data.length; i++) {
                        html += '<span onclick="selectAjax(this, \'' + field + '\')" data-id="' + ret.data[i][id] + '">';
                        html += HTMLEncode(ret.data[i][show]) + '(' + id + ':' + ret.data[i][id] + ')';
                        html += '</span><br/>';
                    }
                    // search_field_List
                    $("#search_" + field + "_List").html(html);
                    $("#search_" + field + "_List").show();
                } else {
                    $("#search_" + field + "_List").html('');
                    $("#search_" + field + "_List").hide();
                }
            },
            complete: function () {
                //layer.close(layerIdx);
            }
        });
    }

    // 搜索的展示
    function selectAjax(obj, field) {
        var fieldID = $(obj).attr('data-id');
        var fieldName = $(obj).text();

        // 如果是单选择
        $("#search_" + field).val(fieldID);
        $("#show_" + field + "_ID").val(fieldName);
        //$("#show_" + field + "_ID").html(field + "：" + fieldID);

        $("#search_" + field + "_List").html('');
        $("#search_" + field + "_List").hide();
    }

    function HTMLEncode(html) {
        var temp = document.createElement("div");
        (temp.textContent != null) ? (temp.textContent = html) : (temp.innerText = html);
        var output = temp.innerHTML;
        temp = null;
        return output;
    }

    // 认证（待删除）
    function renzhen(id) {
        var index = layer.open({
            type: 2,
            title: "认证",
            content: "{sp:U('Manage/Users/renzhen')}?id=" + id
        });
        layer.full(index);
    }

    // 批量操作（待删除）
    function batchOp(type) {
        var txt = '';
        switch (type) {
            case "reduceJifen":
                if (jifen > 0) {
                    txt = '确认要减少积分？'
                } else {
                    editJifen('reduceJifen');
                    return;
                }
                break;
            case "addJifen":
                if (jifen > 0) {
                    txt = '确认要增加积分？'
                } else {
                    editJifen('addJifen');
                    return;
                }
                break;
            case "shenhe":
                txt = '确认要审核？'
                break;
            case "quxiaoshenhe":
                txt = '确认要取消审核？'
                break;
            case "delUsers":
                txt = '确认要删除？'
                break;
            case "xitongxiaoxi":
                if (xitongxiaoxi != '') {
                    txt = '确认要发送系统消息？'
                } else {
                    xitongxiaoxiFunc();
                    return;
                }
                break;
        }
        var ids = '';
        $("input[name='id']:checked").each(function () {
            ids += $(this).val() + ',';
        });
        if (ids == '') return;
        layer.confirm(txt, function (index) {
            layer.closeAll('dialog');
            $.ajax({
                beforeSend: function () {
                    layerIdx = layer.load();
                },
                type: "POST",
                async: false,
                dataType: "json",
                url: "{sp:U('API/Users/batchOp')}",
                data: {
                    ids: ids,
                    type: type,
                    jifen: jifen,
                    xitongxiaoxi: xitongxiaoxi,
                    r: Math.random()
                },
                error: function (XmlHttpRequest, textStatus, errorThrown) {

                },
                success: function (ret) {
                    if (ret.status) {
                        jifen = 0;
                        xitongxiaoxi = '';
                        layer.closeAll();
                        getPageList();
                        //$("#checkAll").click();
                    }
                },
                complete: function () {
                    layer.close(layerIdx);
                }
            });
        });
    }

    // 添加积分（待删除）
    function editJifen(type) {
        layer.open({
            type: 1,
            skin: 'layui-layer-rim', //加上边框
            area: ['420px', '240px'], //宽高
            content: '<div id="chooseClass">'
                + '<input type="text" value="" id="jifen" class="input"/>'
                + '<a href="javascript:;" onclick="doClick(\'' + type + '\');" class="btn btn-success radius">确认</a>'
                + '</div>'
        });
    }

    function doClick(type) {
        jifen = $('#jifen').val();
        layer.closeAll();
        console.log(jifen);
        $("#" + type).click();
    }

    //设置权限
    function xitongxiaoxiFunc() {
        layer.open({
            type: 1,
            skin: 'layui-layer-rim', //加上边框
            area: ['420px', '240px'], //宽高
            content: '<div id="chooseClass">'
                + '<input type="text" value="" id="re_xitongxiaoxi" class="input"/>'
                + '<a href="javascript:;" onclick="doXiaoxiClick();" class="btn btn-success radius">确认</a>'
                + '</div>'
        });
    }

    //
    function doXiaoxiClick() {
        xitongxiaoxi = $('#re_xitongxiaoxi').val();
        layer.closeAll();
        $('#xitongxiaoxi').click();
    }
</script>
